package fun.easycode.webterminal.adapter.api;

import fun.easycode.webterminal.common.contract.R;
import fun.easycode.webterminal.service.dto.SftpFileContentDTO;
import fun.easycode.webterminal.service.SftpService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

/**
 * SFTP 文件编辑控制器
 */
@Slf4j
@RestController
@RequestMapping("/api/sftp/edit")
@RequiredArgsConstructor
public class SftpFileEditApi {

    private final SftpService sftpService;

    /**
     * 获取文件内容
     * @param id 连接ID
     * @param path 文件路径
     * @return 文件内容和元数据
     */
    @GetMapping("/content")
    public R<SftpFileContentDTO> getFileContent(@RequestParam String id, @RequestParam String path) {
        try {
            SftpFileContentDTO content = sftpService.getFileContent(id, path);
            return R.success(content);
        } catch (Exception e) {
            log.error("获取文件内容失败: id={}, path={}", id, path, e);
            return R.error("获取文件内容失败: " + e.getMessage());
        }
    }

    /**
     * 保存文件内容请求 DTO
     */
    public static class SaveFileContentRequest {
        private String id;
        private String path;
        private String content;
        private Long lastModified;

        // Getters and Setters
        public String getId() { return id; }
        public void setId(String id) { this.id = id; }
        public String getPath() { return path; }
        public void setPath(String path) { this.path = path; }
        public String getContent() { return content; }
        public void setContent(String content) { this.content = content; }
        public Long getLastModified() { return lastModified; }
        public void setLastModified(Long lastModified) { this.lastModified = lastModified; }
    }

    /**
     * 保存文件内容
     * @param request 保存请求
     * @return 保存结果
     */
    @PostMapping("/save")
    public R<Void> saveFileContent(@RequestBody SaveFileContentRequest request) {
        try {
            return sftpService.saveFileContent(request.getId(), request.getPath(), request.getContent(), request.getLastModified());
        } catch (Exception e) {
            log.error("保存文件内容失败: id={}, path={}", request.getId(), request.getPath(), e);
            return R.error("保存文件内容失败: " + e.getMessage());
        }
    }
}
